package com.ji.storm.TestStorm.bolt;

import java.util.HashMap;
import java.util.Map;

import com.ji.storm.TestStorm.cons.Const;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;

public class WordCountBolt extends BaseRichBolt {
	private OutputCollector collector;
	private HashMap<String, Long> count;

	@Override
	public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
		this.collector = collector;
		this.count = new HashMap<>();
	}

	@Override
	public void execute(Tuple input) {
		String word = input.getStringByField(Const.WORD);
		Long time = count.get(word);
		if (time == null) {
			time = 0l;
		}
		// System.out.println("########" + count);
		time++;
		this.count.put(word, time);
		this.collector.emit(new Values(word, time));
	}

	@Override
	public void declareOutputFields(OutputFieldsDeclarer declarer) {
		declarer.declare(new Fields(Const.WORD, Const.COUNT));
	}

}
